<?php
	/**
	* @File name:	controller.php
	* @Desription:	controller
	* @Author:	 	jinxin<jx@178.com>   
	* @Date:	 	Tue Jun 14 14:29:09 CST 2011
	* @Copyright 	Copytright (c) 2008-2011 178.COM Co., Ltd.
	* @version	 	$Id $
	*/
	
	class controller{
		public $app;
		public $controller;
		public $action;
		
		/**
		 * 模板视图
		 * @var string
		 */
		
		public $_view;
		
		/**
		 * 模板根路径
		 * @var string
		 */
		
		public $viewRoot;
		
		/**
		 * 用户登录信息
		 * @var array
		 */
		
		public static $login;
		
		/**
		 * 渲染类类型 array('include','single','json','static')
		 * @var array
		 */
		
		public $randerType = array('include','single','json','static');
		
		/**
		 * 渲染模式 (默认include)
		 * @var string
		 */
		
		public $rander = 'include';
		
		/**
		 * 站点
		 * @var string
		 */
		
		public $site;
		
		/**
		 * 框架视图
		 * @var string
		 */
		
		public $frameView;
		
		/**
		 * 登录状态
		 * @var bool
		 */
		
		public $loginStatus;
		
		/**
		 * 模板参数
		 * @var array
		 */
		public $attr = array();
		
		/**
		 * 静态文件路径
		 * @var string
		 */
		
		public $staticPath = null;
		
		/**
		 * 应用配置根路径
		 * @var string
		 */
		
		public $appConfRoot;
		
		/**
		 * 构造函数
		 * @param 应用模块 $app
		 * @param 控制器 $controller
		 * @param 站点 $site
		 */
		public function __construct($app,$controller,$site){
			$this->app = $app;
			$this->controller = $controller;
			$this->site = str_replace('_',DIRECTORY_SEPARATOR,$site);
			$this->viewRoot = SCRIPT_PATH.str_replace('_',DIRECTORY_SEPARATOR,$site.$app.'_views');
			$this->appConfRoot = SCRIPT_PATH.str_replace('_',DIRECTORY_SEPARATOR,$site.$app.'_configs_');
			$this->frameView = $this->viewRoot.DIRECTORY_SEPARATOR.'frame.phtml';
			if (is_dir($this->appConfRoot)) {
				$files = scandir($this->appConfRoot);
				$appConf = array();
				foreach ($files as $confile){
					if (substr($confile,-4) == '.php'){
						include_once($this->appConfRoot.$confile);
					}
				}
			}
			
			$this->loginStatus = $this->checkLogin();
			if ($_SERVER['HTTP_HOST'] == $_SERVER['config']['phpsite']['admin'] && $this->loginStatus == false && $this->app != 'login'){
				$param = $_SERVER['REQUEST_URI'] != '/' ? array('to'=>$_SERVER['REQUEST_URI']) : array();
				header('Location: http://'.$_SERVER['HTTP_HOST'].self::_getUri('login','index','form',$param));
			}
		}
		
		/**
		 * 析构函数
		 */
		public function __destruct(){}
		
		/**
		 * 检查登录状态
		 */
		public function checkLogin(){
			if ($_SESSION['uid'] > 0 || (isset($_COOKIE['admin_sid']) && isset($_COOKIE['admin_uid']) && $_COOKIE['admin_sid'] == $_SESSION['SID'] && $_COOKIE['admin_uid'] > 0)) {
				if (!$_COOKIE['admin_id']) {
					setcookie('admin_sid',$_SESSION['SID'],time()+3600,'/',$_SERVER['config']['domain']['admin']);
					setcookie('admin_uid',$_SESSION['uid'],time()+3600,'/',$_SERVER['config']['domain']['admin']);
					setcookie('admin_author',$_SESSION['username'],time()+3600,'/',$_SERVER['config']['domain']['admin']);
					setcookie('admin_group_id',$_SESSION['group_id'],time()+3600,'/',$_SERVER['config']['domain']['admin']);
				}
				self::$login['uid'] = $_COOKIE['admin_uid'];
				self::$login['username'] = $_COOKIE['admin_author'];
				self::$login['group_id'] = $_COOKIE['admin_group_id'];
				return true;
			}else {
				return false;
			}
		}
		
		/**
		 * 执行action
		 * @param object $action
		 * @throws Exception
		 */
		public function launch($action){
			$this->action = $action;
			$this->$action();
			if (in_array($this->rander,$this->randerType)){
				if (!empty($this->attr)){
					extract($this->attr,EXTR_OVERWRITE);
				}
				switch ($this->rander){
					case 'include':
						if (!is_file($this->frameView)){
							throw new Exception('no_tpl');
						}
						$this->_view = (is_null($this->_view) || $this->_view == '') ? $this->action : $this->_view;
						include_once(VIEW_PATH.$this->site.DIRECTORY_SEPARATOR.'frame.phtml');
						break;
					case 'single':
						$this->_view = (is_null($this->_view) || $this->_view == '') ? $this->action : $this->_view;
						$viewPath = $this->_view != 'hint' ? $this->viewRoot.DIRECTORY_SEPARATOR.$this->controller.DIRECTORY_SEPARATOR.$this->_view.'.phtml' : VIEW_PATH.'hint.phtml';
						if (!is_file($viewPath)){
							throw new Exception('no_tpl');
						}
						include_once($viewPath);
						break;
					case 'json':
						include_once(VIEW_PATH.'json.phtml');
						break;
					case 'static':
						$this->_view = (is_null($this->_view) || $this->_view == '') ? $this->action : $this->_view;
						$viewPath = $this->_view != 'hint' ? $this->viewRoot.DIRECTORY_SEPARATOR.$this->controller.DIRECTORY_SEPARATOR.$this->_view.'.phtml' : VIEW_PATH.'hint.phtml';
						if (!is_file($viewPath)){
							throw new Exception('no_tpl');
						}
						include_once($viewPath);
						if ($this->staticPath) {
							ob_start();
							$tpl = ob_get_contents();
							ob_end_clean();
							file_put_contents($this->staticPath,$tpl);
						}
						break;
				}
			}
			
		}
		
		/**
		 * 格式化打印数据
		 * @param mix $data
		 */
		public function dump($data){
			echo '<pre>';
			print_r($data);
			echo '</pre>';
		}
		
		/**
		 * 生成url
		 * @param string $app
		 * @param string $controller
		 * @param string $action
		 * @param array $params
		 */
		public static function _getUri($app,$controller,$action,$params=array()){
			$p = array();
			$url = '';
			if (!empty($params)){
				foreach ($params as $key=>$value){
					if ($key && $value!=''){
						if (strpos($key,'_uri') !== false) {
							$url = '/?'.$key.'='.rawurlencode($value);
						}else {
							$p[] = $key.'/'.$value;
						}
					}
				}
			}
			return $uri = '/'.$app.'/'.$controller.'/'.$action.(!empty($p) ? '/'.implode('/',$p) : '').$url;
		}
		
		/**
		 * 跳转页面
		 * @param string $msg
		 * @param string $status
		 * @param string $to
		 */
		public function hint($msg,$status='access',$to=''){
			$this->attr['msg'] = $msg;
			$this->attr['status'] = $status;
			$this->attr['to'] = $to == '' ? '/' : $to;
			$this->rander = 'single';
			$this->_view = 'hint';
		}
		
		/**
		 * 加载视图
		 * @throws Exception
		 */
		public function view(){
			$viewPath = $this->viewRoot.DIRECTORY_SEPARATOR.$this->controller.DIRECTORY_SEPARATOR.$this->_view.'.phtml';
			if (!is_file($viewPath)){
				throw new Exception('no_tpl');
			}
			if (!empty($this->attr)){
				extract($this->attr,EXTR_OVERWRITE);
			}
			$header = $this->viewRoot.DIRECTORY_SEPARATOR.$this->controller.DIRECTORY_SEPARATOR.'_header.phtml';
			if (is_file($header)) {
				include_once($header);
			}
			include_once($viewPath);
		}
		
		/**
		 * 生成分页代码
		 * @param array $pageInfo
		 * @param array $params
		 */
		public function genPage($pageInfo,$params=array()){
			if ($pageInfo['pagecount'] > 1) {
				$ret = '';
				$current = $pageInfo['page'];
				$pages = array();
				$option = $hidden = '';
				for($i=$pageInfo['page']-2; $i<=$pageInfo['pagecount']; $i++){
					if($i<=0) continue;
						array_push($pages, array($i, $i));
					if(count($pages)==5) break;
				}
				if($pageInfo['page']-1>0)	array_unshift($pages, array($pageInfo['page']-1, '上一页'));
				if($pageInfo['page']+1<=$pageInfo['pagecount'])	array_push($pages, array($pageInfo['page']+1, '下一页'));
				$page_string = ' <a href="%s" class="%s">%s</a> ';
				$page_url = $this->_getUri($this->app, $this->controller,$this->action, $params);
				foreach($pages as $a){
					$ret.=sprintf($page_string, $page_url."/page/".$a[0], ($a[0]==$current)?"pselected":"", $a[1]);
				}
				return '<div class="pages">'.$ret.'<span>总共'.$pageInfo['pagecount'].'页</span>'.'</div>';
			}else {
				return '<p class="page">共1页</p>';
			}
		}
		
		/**
		 * 格式化$_GET参数
		 * @param 参数名 string $p
		 * @param 参数类型 string $type
		 * @param 默认值 string $def
		 */
		public function _fget($p,$type='int',$def=0){
			$types = array('int','string');
			switch ($type){
				case 'int':
					return isset($_GET[$p]) && (int)$_GET[$p] > 0 ? (int)$_GET[$p] : $def;
					break;
				case 'string':
					return isset($_GET[$p]) && (string)trim($_GET[$p]) != '' ? (string)$this->_addslashes(trim($_GET[$p])) : $def;
					break;
			}
		}
		
		/**
		 * 格式化$_POST参数
		 * @param 参数名 string $p
		 * @param 参数类型 string $type
		 * @param 默认值 string $def
		 */
		public function _fpost($p,$type='int',$def=0){
			$types = array('int','string');
			switch ($type){
				case 'int':
					return isset($_POST[$p]) && (int)$_POST[$p] > 0 ? (int)$_POST[$p] : $def;
					break;
				case 'string':
					return isset($_POST[$p]) && (string)trim($_POST[$p]) != '' ? (string)$this->_addslashes(trim($_POST[$p])) : $def;
					break;
			}
		}
		
		/**
		 * 转义特殊字符
		 * @param string $str
		 */
		public function _addslashes($str){
			if (get_magic_quotes_gpc() == 0) {
				return addslashes($str);
			}else {
				return $str;
			}
		}
		
		/**
		 * 判断数组是否为空
		 * @param array $array
		 */
		public function _empty($array){
			if (empty($array)) {
				return true;
			}
			$flag = false;
			foreach ($array as $value){
				if ($value != '' || $value > 0) {
					$flag = true;
				}
			}
			if ($flag == true) {
				return false;
			}
			return true;
		}
		
		/**
		 * 直接跳转页面
		 * @param string $url
		 */
		public function _location($url){
			header('Location: '.$url);
		}
		
		/**
		 * 包含视图
		 * @param string $tpl_name
		 */
		public  function _includeTpl($tpl_name){
			$path = $this->viewRoot.DIRECTORY_SEPARATOR.$this->controller.DIRECTORY_SEPARATOR;
			$filename = $tpl_name.'.phtml';
			if (!empty($this->attr)){
				extract($this->attr,EXTR_OVERWRITE);
			}
			if (is_file($path.$filename)) {
				include($path.$filename);
			}
		}
	}